// 新增常量定义
const ERROR_MESSAGES = {
    401: '登录状态已过期',
    500: '服务器开小差了',
    network: '网络连接异常'
}
const apiUrl = process.env.VUE_APP_BRACELET_API
// const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
// let result = '';
// const charactersLength = characters.length;
// for (let i = 0; i < 16; i++) {
//     result += characters.charAt(Math.floor(Math.random() * charactersLength));
// }

const showErrorToast = (error) => {
    const serverMsg = (error && (String(error).includes("服务器内部错误") || error?.message?.includes("服务器内部错误"))) ? '服务器内部错误' : (error?.data?.message || error?.errMsg || error || error?.message || '未知错误');
    const isNetworkError = error?.errMsg?.includes("request:fail") || error?.errMsg?.includes("timeout") || error?.errMsg?.includes("Network Error")  || error?.includes("Not Found");
    uni.showToast({
        icon: 'none',
        title: isNetworkError ? '网络连接异常' : (serverMsg || '请求失败'),
        duration: 2000
    });
};

// 封装生成随机字符串的函数
function generateRandomString(length) {
    let result = '';
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

function generateRequestId() {
    const prefix = "miniprogram-req-";
    const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let randomPart = "";
    
    // 生成30位随机字符串
    for (let i = 0; i < 30; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      randomPart += characters.charAt(randomIndex);
    }
    
    // 拼接并返回完整的请求ID
    return prefix + randomPart;
}
  

// 不需要登录
const baseIndexRequest = (url, method, params, contentType) => {
    // const curDate=new Date().getTime()
    // const randomString = generateRandomString(16);
    // const noLoginRequestId = randomString + curDate;
    const noLoginRequestId = generateRequestId()

    return new Promise((resolve, reject) => {
        uni.request({
            url: apiUrl + url, // 测试接口
            method: method,
            data: params,
            header: {
                'content-type': contentType || 'application/json',
                // 'X-Request-Id':'miniprogram-req-'+ noLoginRequestId
                'X-Request-Id':noLoginRequestId
            }
        }).then((response) => {
            console.log(response, 'response')
            const res = response

            if (res.statusCode === 500) {
                uni.showToast({
                    icon: 'none',
                    title: res.data.message || '服务器内部错误',
                    duration: 2000
                })
                return Promise.reject( res.data.message)
            }else if (res.statusCode === 401 || res.data.code === -1) {
                // 接口出问题，可能是token失效了，返回登陆页
                uni.clearStorage()
                uni.navigateTo({
                    url: '/pages/login/loginSelect'
                })
            } else {
                resolve(res.data,'res.data')
            }
        }).catch(error => {
            console.log(error,'error错误啊')
            const serverMsg = (error && (String(error).includes("服务器内部错误") || error?.message?.includes("服务器内部错误")) ) ? '服务器内部错误' : (error?.data?.message || error?.errMsg || error || error?.message || '未知错误')
            const isNetworkError = error?.errMsg?.includes("request:fail") || error?.errMsg?.includes("timeout") || error?.errMsg?.includes("Network Error")            // 弹出消息提示
            uni.showToast({
                icon: 'none', // 不显示图标，最多显示2行
                title: isNetworkError ? '网络连接异常' : (serverMsg || '请求失败'),
                duration: 2000
            })
            return Promise.reject(error)
            // resolve(error,'error')
        })
    })
}


// 开始不需要登录 但是有事件 要登录 重新调接口  需要先调用refreshToken接口
const baseRequest = (url, method, params, contentType) => {
    const token = uni.getStorageSync('access_token')
    const refreshToken = uni.getStorageSync('refreshToken')
    // const current = new Date().getTime()

    // const randomString = generateRandomString(16);
    // const requestId = randomString + current;
    const requestId = generateRequestId()

    // 新增 GET 请求处理逻辑
    const isGetWithBody = method.toLowerCase() === 'get' && contentType === 'application/json';
    const finalUrl = isGetWithBody ? `${apiUrl}${url}` : apiUrl + url;
    const finalMethod = isGetWithBody ? 'POST' : method; // 兼容处理

    return new Promise((resolve, reject) => {
        const headers = {
            'Content-Type': contentType || 'application/json',
            'X-Request-Id': requestId,
            'X-Method-Override': isGetWithBody ? 'GET' : null
        };
        if (token) {
            headers['Authorization'] = 'Bearer ' + token;
        }
        // console.log('Headers:', headers);
        uni.request({
            url: apiUrl + url, // 测试接口
            method: finalMethod,
            data: params,
            header: headers
            // header: {
            //     'Content-Type': contentType || 'application/json',
            //     // 'Authorization': 'Bearer ' + token,
            //     ...(token ? { 'Authorization': 'Bearer ' + token } : {}), // 动
            //     'X-Request-Id': 'miniprogram-req-' + requestId,
            //     'X-Method-Override': isGetWithBody ? 'GET' : null // 添加方法重写头
            // }
        }).then((response) => {
            const res = response
            if (res.statusCode === 500 || res.data.code === 500) {
                uni.showToast({
                    icon: 'none',
                    title: res.data.message || '服务器内部错误',
                    duration: 2000
                })
                return Promise.reject(res.data.message || 'Internal Server Error')
            } else if (res.statusCode === 401 || res.data.code === -1 || ( token && (res.data.accessTokenExpired === "true" || res.data.accessTokenExpired === true ))) {
                // 当存在token时尝试刷新
                if (token) {
                    // const currentDate = new Date().getTime()
                    // const newrequestId = currentDate
                    const newrequestId = generateRequestId()
                    uni.request({
                        url: apiUrl + 'api/miniProgram/refresh',
                        method: 'POST',
                        header: {
                            'Content-Type': contentType || 'application/json',
                            'Authorization': refreshToken,
                            // 'X-Request-Id': 'miniprogram-req-' + newrequestId
                            'X-Request-Id': newrequestId
                        }
                    }).then((newResponse) => {
                        console.log(newResponse, 'newResponse---++++')
                        const newRes = newResponse
                        if (res.statusCode === 500) {
                            uni.showToast({
                                icon: 'none',
                                title: res.data.message || '服务器内部错误',
                                duration: 2000
                            })
                            return Promise.reject(res.data.message)
                        } else if (newRes.statusCode === 401 || newRes.data.code === -1 || newRes.data.refreshExpiredCode === true || (newRes.statusCode === 401 && newRes.data.refreshExpiredCode === false)) {
                            uni.clearStorage()
                            uni.navigateTo({
                                url: '/pages/login/loginSelect'
                            })
                        } else if (newRes.data.refreshExpiredCode === false) {
                            const access_token = newRes.data.token
                            const refreshToken = newRes.data.refreshToken
                            uni.setStorage({ key: 'access_token', data: access_token })
                            uni.setStorage({ key: 'refreshToken', data: refreshToken })
                            // const newcurrentDate = new Date().getTime()
                            // const newRequestId = newcurrentDate
                            const secondRequestId = generateRequestId()
                            uni.request({
                                url: apiUrl + url, // 测试接口
                                method: method,
                                data: params,
                                header: {
                                    'Content-Type': contentType || 'application/json',
                                    'Authorization': 'Bearer ' + access_token,
                                    // 'X-Request-Id': 'miniprogram-req-' + newRequestId
                                    'X-Request-Id': secondRequestId
                                }
                            }).then((response1) => {
                                const res1 = response1
                                resolve(res1.data)

                            }).catch(error => {
                                console.log(error, 'error request')
                                showErrorToast(error)
                                // const serverMsg = error.data?.msg || error?.errMsg || error || error?.message
                                // const isNetworkError = error.errMsg.includes("request:fail") || error.errMsg.includes("timeout") || error.errMsg.includes("Network Error")
                                // // 弹出消息提示
                                // uni.showToast({
                                //     icon: 'none', // 不显示图标，最多显示2行
                                //     title: isNetworkError ? '网络连接异常' : (serverMsg || '请求失败'),
                                //     duration: 2000
                                // })
                                return Promise.reject(error)
                            })
                        }

                    }).catch((newError) => {
                        console.log(newError);
                        showErrorToast(newError)
                        // const serverMsg = (newError && (String(newError).includes("服务器内部错误") || newError?.message?.includes("服务器内部错误"))) ? '服务器内部错误' : (newError?.data?.msg || newError?.errMsg || newError || newError?.message || '未知错误')
                        // const isNetworkError = newError?.errMsg?.includes("request:fail") || newError?.errMsg?.includes("timeout") || newError?.errMsg?.includes("Network Error")                    // 弹出消息提示
                        // uni.showToast({
                        //     icon: 'none', // 不显示图标，最多显示2行
                        //     title: isNetworkError ? '网络连接异常' : (serverMsg || '请求失败'),
                        //     duration: 2000
                        // })
                        return Promise.reject(newError)
                    });
                }else{
                    // 无token直接跳转登录
                    uni.clearStorage();
                    uni.navigateTo({ url: '/pages/login/loginSelect' });
                }
            } else if (res.data.refreshExpiredCode === true) {
                // 接口出问题，可能是token失效了，返回登陆页
                uni.clearStorage()
                uni.navigateTo({
                    url: '/pages/login/loginSelect'
                })
            } else {
                resolve(res.data)
            }
        }).catch(finalError => {
            console.log(finalError, 'error request')
            showErrorToast(finalError)

            // return Promise.reject(finalError)
            resolve(finalError)
        })
    })
}

export default {
    baseRequest,
    baseIndexRequest
}
